import {createSlice} from "@reduxjs/toolkit";
import {request} from '@/utils'
import {setToken as _setToken, getToken, removeToken} from "../../utils";
import {getUserInfoApi, userLoginApi} from "../../apis/user";

const userStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            // localStorage.setItem('token_key', action.payload)
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
});


const {setToken, setUserInfo, clearUserInfo} = userStore.actions

const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await userLoginApi(loginForm);
        dispatch(setToken(res.data.token))
    }
}

const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfoApi()
        dispatch(setUserInfo(res.data))
    }
}

const userReducer = userStore.reducer;

export {fetchLogin, setToken, fetchUserInfo, clearUserInfo}

export default userReducer
